package com.lmx.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.MessageService;
import com.lmx.persistence.service.WorkOrderService;
import com.lmx.repoDomain.tmodel.business.User;//huibati
import com.lmx.thirdPart.daerma.DaermaBusinessProcessor;

import net.sf.json.JSONObject;

import com.lmx.repoDomain.tmodel.Workorder;
import com.lmx.repoDomain.tmodel.WorkorderPageInfo;

@Controller
@RequestMapping("/thirdPart")
public class ThridPartController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    WorkOrderService workorderService;
    
    @Autowired
    MessageService messageService;
    
    @Autowired
    HttpServletRequest request;
    
    //获取工单列表
    @RequestMapping(value = "/getWorkorderList", method = RequestMethod.GET)
    public String  getWorkorderList(ModelMap model,WorkorderPageInfo workorderPageInfo) {
    	
    	Map<String ,Object> values = new HashMap<String ,Object>();
    	
    	//验证当前页数
    	if(!String.valueOf(workorderPageInfo.getPage()).isEmpty()){
    		int pageNum = (workorderPageInfo.getPage()-1)*workorderPageInfo.getSize();
    		values.put("pageNum", pageNum);
    		values.put("size", workorderPageInfo.getSize());
    		model.put("page", workorderPageInfo.getPage());
    	}else{
    		model.put("erroMessage", "参数错误");
    		return "page/erro";
    	}
    	
    	//企业用户名
    	String companyLoginName = workorderPageInfo.getCompanyLoginName();
    	values.put("companyLoginName", companyLoginName);
    	model.put("companyLoginName", companyLoginName==null?companyLoginName="":companyLoginName);
    	
		//任务名
		String taskName = workorderPageInfo.getTaskName();
		values.put("taskName", taskName);
    	model.put("taskName", taskName==null?taskName="":taskName);
    	
		//客服用户名
		String createloginName = workorderPageInfo.getCreateloginName();
		values.put("createloginName", createloginName);
    	model.put("createloginName", createloginName==null?createloginName="":createloginName);
    	
		//状态
		String isSuccess = workorderPageInfo.getIsSuccess();	
		values.put("isSuccess", isSuccess);
    	model.put("isSuccess", isSuccess==null?isSuccess="":isSuccess);
    	
    	String startTime = workorderPageInfo.getStartTime();//开始时间
    	values.put("startTime", startTime);
    	model.put("startTime", startTime==null?startTime="":startTime);
    	
    	String enTime = workorderPageInfo.getEnTime();//截止时间
    	values.put("enTime", enTime);
    	model.put("enTime", enTime==null?enTime="":enTime);
    	
    	//获取工单列表
    	List<Map<String ,Object>> workorderList = workorderService.getWorkOrderList(values);
    	//获取工单列表总条数
    	int count = workorderService.getWorkOrderListCount(values);
    	
    	model.put("workorderList", workorderList);
    	model.put("count", count);
    	
        return "page/business/workorderList";
    }    
    
    
    //获取工单详情
    @RequestMapping(value = "/getWorkorder", method = RequestMethod.GET)
    public String  getWorkorder(ModelMap model,WorkorderPageInfo workorderPageInfo) {
    	//验证workOrderID
    	Long workOrderID = workorderPageInfo.getWorkOrderID();
    	if(workOrderID == null){
    		model.put("erroMessage", "参数错误");
    		return "page/erro";
    	}
    	
    	Map<String ,Object> wordorderMap = workorderService.getWorkOrder(workOrderID);
    	
    	model.put("wordorderMap", wordorderMap);
    	model.put("workOrderID", workOrderID.toString());
    	String url = workorderPageInfo.getUrl();
    	model.put("url", url==null?url="":url);
    	HttpSession session = request.getSession(); 
    	session.setAttribute("url", url==null?url="":url); 
    	session.setMaxInactiveInterval(120*60);//设置失效时长为2小时
    	
        return "page/business/workorder";
    }
    
    //修改成单状态
    @RequestMapping(value = "/updateWorkorderIsSuccess", method = RequestMethod.GET)
    @ResponseBody
    public String  updateWorkorderIsSuccess(String workOrderID,String isSuccess) {
    	String json = "";
    	Map<String ,Object> msgMap = new HashMap<String ,Object>();
    	Workorder workorder = new Workorder();
    	//验证workOrderID
    	if(workOrderID != null && !workOrderID.isEmpty()){
    		workorder.setId(Long.valueOf(workOrderID));
        }else{
        	msgMap.put("flag", 0);
            json = CommonUtil.mapToJsonString(msgMap);
            return json;
        }
        	
        //验证isSuccess
        if(isSuccess != null && !isSuccess.isEmpty()){
        	workorder.setIsSuccess(Short.parseShort(isSuccess));
        }else{
        	msgMap.put("flag", 0);
            json = CommonUtil.mapToJsonString(msgMap);
            return json;
        }
        //修改成单状态
        workorderService.updateWorkorderIsSuccess(workorder);
        //发送工单提醒
        messageService.workorderRemind(workorder,ICommonConstants.THAWTYPE.BACK.ordinal());
    	msgMap.put("flag", 1);
    	json = CommonUtil.mapToJsonString(msgMap);
        return json;
    }    
    
    
    

    public String post(String url, Map<String, String> header, String argument)
 			throws ClientProtocolException, IOException {
 		CloseableHttpClient client = HttpClients.createDefault();
 		HttpPost post = new HttpPost(url);
 		for (Map.Entry<String, String> element : header.entrySet()) {
 			post.addHeader(element.getKey(), element.getValue());
 		}
 		StringEntity entityPara = new StringEntity(argument, "utf-8");// 解决中文乱码问题
 		post.setEntity(entityPara);
 		CloseableHttpResponse response = client.execute(post);
 		return EntityUtils.toString(response.getEntity());
 	}
    
    /*
     * 获取离床的状态
     */
    @RequestMapping(value = "/leavingBed", method = RequestMethod.POST)
    @ResponseBody
    public String  getLeavingMattress(@RequestBody String param) {
    	
    	
    	logger.info("param in getLeavingMattress:" + param.toString());	

    	
    	String json = "123";
    	
        return json;
    }
}
